﻿using System.Collections.ObjectModel;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using IMClient.Cache.Repositories;
using IMClient.Model;
using IMClient.Model.DataBase;
using IMClient.Model.UI;
using IMClient.View;

namespace IMClient.ViewModels
{
    public partial class ContactsPageFriendsListViewModel : ObservableObject
    {
        [ObservableProperty]
        private ObservableCollection<FriendViewModel> friendsList;

        [ObservableProperty]
        private ObservableCollection<FriendViewModel> filteredFriends;

        [ObservableProperty]
        private FriendViewModel? selectedFriend; // 当前选中的好友


        private readonly FriendCacheRepository _friendRepository;
        
        public event Action<object>? CurrentViewChanged;
        public ContactsPageFriendsListViewModel() 
        {
            _friendRepository = FriendCacheRepository.Instance;
            FriendsList = new ObservableCollection<FriendViewModel>();
            filteredFriends=new ObservableCollection<FriendViewModel>();

            // 监听好友列表更新事件
            User.OnFriendListUpdated += () =>
            {
                _ = LoadFriendsAsync();
            };
            
            _ = LoadFriendsAsync();
        }

        [RelayCommand]
        private void ShowFriendDetails()
        {
            if (SelectedFriend != null)
            {
                // 触发事件或逻辑以通知外部显示好友详情视图
                CurrentViewChanged?.Invoke(new FriendDetailsView
                {
                    DataContext = new FriendDetailsViewModel(SelectedFriend)
                });
            }
        }

        private async Task LoadFriendsAsync()
        {
            try
            {
                string userId = User.UserId ?? throw new InvalidOperationException("用户ID不能为空");

                // 从数据库加载好友列表
                var cachedFriends = await _friendRepository.GetCachedFriendsAsync(userId);
                UpdateUIFriendsList(cachedFriends);
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    MessageBox.Show($"加载好友列表失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                });
            }
        }

        private void UpdateUIFriendsList(List<FriendDataBase> friends)
        {
            Application.Current.Dispatcher.BeginInvoke(() =>
            {
                FriendsList.Clear();
                FilteredFriends.Clear();
                foreach (var friend in friends)
                {
                    FriendsList.Add(new FriendViewModel
                    {
                        Id = friend.FriendId,
                        Name = friend.FriendName,
                        Avatar = friend.FriendAvatar,
                        IsFriend = true,
                        ButtonText = "已是好友"
                    });
                    FilteredFriends.Add(new FriendViewModel
                    {
                        Id = friend.FriendId,
                        Name = friend.FriendName,
                        Avatar = friend.FriendAvatar,
                        IsFriend = true,
                        ButtonText = "已是好友"
                    });
                }

                if (FilteredFriends.Count > 0)
                {
                    SelectedFriend = FilteredFriends[0];
                }
            });
        }
    }
}
